package com.epfresh.views.dialog;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.T;
import com.epfresh.bean.GoodsDetail;
import com.epfresh.utils.FormatUtil;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by wzh on 16-7-13.
 */
public class AddCartDialog extends BaseDialogView implements View.OnClickListener {

    public interface OnAddCartListener {
        public void onAddCart(double cnt);
    }

    TextView tvUnitPrice;
    TextView tvInventory;
    TextView tvLeast;
    TextView tvChargeUnit;
    TextView tvIntro;
    TextView tvPackageHint;
    TextView tvPackage;
    EditText edCnt;
    ImageView ivLogo;

    GoodsDetail goodsDetail;

    OnAddCartListener onAddCartListener;
    //    TextWatcher ta;
    double min = 0.01;
    double max = 99999;
    double incr = 0.01;


    public AddCartDialog(Context context) {
        super(context);

        init();
    }

    public OnAddCartListener getOnAddCartListener() {
        return onAddCartListener;
    }

    public void setOnAddCartListener(OnAddCartListener onAddCartListener) {
        this.onAddCartListener = onAddCartListener;
    }

    @Override
    public void initBefore() {
        setGravity(Gravity.BOTTOM);
    }

    @Override
    protected void initAnim() {
        super.initAnim();
    }

    private void init() {

        View v = LayoutInflater.from(context).inflate(R.layout.item_add_cart, contentContainer);

        tvUnitPrice = (TextView) v.findViewById(R.id.tv_unit_price);
        tvInventory = (TextView) v.findViewById(R.id.tv_inventory);
        tvLeast = (TextView) v.findViewById(R.id.tv_min);
        tvChargeUnit = (TextView) v.findViewById(R.id.tv_charge_unit);
        tvIntro = (TextView) v.findViewById(R.id.tv_intro);
        tvPackage = (TextView) v.findViewById(R.id.tv_package);
        tvPackageHint = (TextView) v.findViewById(R.id.tv_package_hint);

        edCnt = (EditText) v.findViewById(R.id.ed_price);
        ivLogo = (ImageView) v.findViewById(R.id.iv_img);

        v.findViewById(R.id.iv_add).setOnClickListener(this);
        v.findViewById(R.id.iv_remove).setOnClickListener(this);
        v.findViewById(R.id.tv_sure_cart).setOnClickListener(this);
        v.findViewById(R.id.iv_cancel).setOnClickListener(this);


        TextWatcher ta = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                String s = editable.toString();
                edCnt.removeTextChangedListener(this);
                if ("".equals(s)) {
//                    edCnt.setText(min + "");
//                    edCnt.setSelection(edCnt.getText().toString().length());
//                    edCnt.addTextChangedListener(this);
//                    updateIntro(min);
//                    return;
                    s = "0";
                }
                double numberFlag = Double.valueOf(s);
//                if (numberFlag < min)
//                    numberFlag = min;
                updateIntro(numberFlag);
//                if ((numberFlag - min) % incr > 0) {
//                    numberFlag = (numberFlag - min) / incr + incr + min;
//                }
//
//                edCnt.setText(numberFlag + "");
//                edCnt.setSelection(edCnt.getText().toString().length());
/*                if (VerificationUtils.isNumeric(s)){
                    int cnt = Integer.valueOf(s);
                    if (cnt < numberFlag){
                        edCnt.setText(""+numberFlag);
                        edCnt.setText(standardNumber(numberFlag)+"");
                    }else if (cnt > numberFlag){
                        edCnt.setText(""+max);
                        edCnt.setText(standardNumber(min)+"");
                    }
                }*/
                edCnt.addTextChangedListener(this);
            }
        };
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 99999;
        edCnt.setFilters(new InputFilter[]{cashierInputFilter});
//        edCnt.addTextChangedListener(ta);
//        edCnt.setEnabled(false);
        setCancelable(true);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add:
                add(true);
                break;

            case R.id.iv_remove:
                add(false);
                break;

            case R.id.tv_sure_cart:

                sure();
                break;
            case R.id.iv_cancel:
                dismiss();
                break;


        }
    }


    public void add(boolean isAdd) {
//
//        String t = edCnt.getText().toString();
//        double cnt = min;
////        if (cnt < min)
////            cnt = min;
//
//
//        if (isAdd) {
//            //cnt++;
//            if (goodsDetail != null && cnt < goodsDetail.getInventoryAmount())
//                cnt = FormatUtil.countAdd(cnt, goodsDetail.getIncr());
//        } else {
//            cnt = FormatUtil.countSubtract(cnt, goodsDetail.getIncr());
//
//        }
//        if (cnt < min) {
//            cnt = min;
//        }
//        cnt = FormatUtil.countFormat(cnt, incr);
//        updateIntro(cnt);
//        edCnt.setText(FormatUtil.subZeroAndDot(cnt + ""));
//        edCnt.setSelection(edCnt.getText().toString().length());

        String t = edCnt.getText().toString();
        double cnt = min;
        double incr = goodsDetail.getIncr();
//        if (cnt < min)
//            cnt = min;
        try {
            cnt = Double.valueOf(t);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (isAdd) {
                //cnt++;
                Double tmp = FormatUtil.countAdd(cnt, incr);

                if (goodsDetail != null) {
                    Double p = goodsDetail.getPromotionItemQuantityPerAccountD();
                    if (p != null && p < tmp) {
                        T.toast("超出限购数量");
                    }else {

//                        if (goodsDetail != null && tmp > goodsDetail.getInventoryAmount()) {
//                            T.toast("库存不足");
//                        }
                        if (goodsDetail != null/* && cnt < goodsDetail.getInventoryAmount()*/) {
                            cnt = FormatUtil.countAdd(cnt, incr);
                        }
                    }
                }
            } else {
                cnt = FormatUtil.countSubtract(cnt, incr);

            }
            if (cnt < min) {
                cnt = min;
            }
            updateIntro(cnt);
            edCnt.setText(FormatUtil.subZeroAndDot(cnt + ""));
            edCnt.setSelection(edCnt.getText().toString().length());
        }
    }

    public void sure() {
        boolean legitimate = isLegitimate();
        if (!legitimate){
            return;
        }
        String t = edCnt.getText().toString();
        double cnt = min;
        try {
            cnt = Double.valueOf(t);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (cnt < min) {
                T.toast("数量少于最小起订量");
                cnt = min;
                return;
            }
            if (cnt > max) {
                T.toast("数量超过库存");
                cnt = max;
                return;
            }

            if (onAddCartListener != null) {
                if (cnt < 0.01) {
                    T.toast("请添加数量");
                } else
                    onAddCartListener.onAddCart(cnt);
            }
        }


    }

    public boolean isLegitimate() {
        boolean isLegitimate = true;
        String s = edCnt.getText().toString();
        if ("".equals(s)) {
            edCnt.setText(FormatUtil.subZeroAndDot(min + ""));
            edCnt.setSelection(edCnt.getText().toString().length());
            return false;
        }
        double numberFlag = Double.valueOf(s);

//        if (numberFlag < min)
//            numberFlag = min;
        incr = incr == 0 ? min : incr;
        if (FormatUtil.isRemainder(numberFlag, incr,min)) {
            numberFlag = FormatUtil.countFormat(numberFlag, incr,min);
            T.toast("已校准数量,请重新加入购物车");
            isLegitimate = false;
        }

        edCnt.setText(FormatUtil.subZeroAndDot(numberFlag + ""));
        updateIntro(numberFlag);
        edCnt.setSelection(edCnt.getText().toString().length());

        return isLegitimate;
    }

    public void show(GoodsDetail goodsDetail, double min) {
        this.goodsDetail = goodsDetail;
        tvIntro.setVisibility(View.INVISIBLE);
        incr = goodsDetail.getIncr();
        if (goodsDetail.isDc()) {
            calMin(goodsDetail);
            max = 999999999;
//                tvLeast.setVisibility(View.GONE);
            tvInventory.setVisibility(View.GONE);
        } else {
            calMin(goodsDetail);
            calMax(goodsDetail);
        }
        if (goodsDetail.getType() == 2){
//            tvUnitPrice.setText(goodsDetail.getDepositStr2()+"元/" + goodsDetail.getChargeUnit());
        }else {
            if (goodsDetail.getProductSpecPrice().isPrePrice()) {
                tvUnitPrice.setText(goodsDetail.getPrice()+"元/" + goodsDetail.getChargeUnit());
            }else {
                tvUnitPrice.setText("时价");
            }

        }
        tvLeast.setText(goodsDetail.getProductSpecPrice().getMoq()+goodsDetail.getChargeUnit());
        tvChargeUnit.setText(goodsDetail.getUnit());
        String pack = goodsDetail.getPack();
//            if (pack == null || "".equals(pack)){
//                tvPackageHint.setVisibility(View.GONE);
//            }else {
//                tvPackageHint.setVisibility(View.VISIBLE);
//            }
        if (!TextUtils.isEmpty(pack)) {
            tvPackage.setText(pack);
        } else {
            tvPackageHint.setVisibility(View.INVISIBLE);
            tvPackage.setVisibility(View.INVISIBLE);
        }

        String price = goodsDetail.getPrice()+"";
        String unit = goodsDetail.getUnit();
//            if (price != null) {
//                String[] split = price.split("/");
//                if (split.length > 1) {
//                    unit = split[1];
//                }
//            }
        tvInventory.setText("库存" + FormatUtil.subZeroAndDot((new BigDecimal(goodsDetail.getInventoryAmount()).toPlainString() + "") )+ unit);
        edCnt.setText(FormatUtil.subZeroAndDot(min + ""));
        updateIntro(min);
        List<String> banners = goodsDetail.getBanner();
        String url = "";
        if (banners != null && banners.size() > 0) {
            url = banners.get(0);
        }

        ImageLoader.getInstance().displayImage(url, ivLogo);
        super.show();
    }

    public void updateIntro(double count) {
        tvIntro.setVisibility(View.INVISIBLE);
        if (this.goodsDetail != null) {
            double incr = goodsDetail.getIncr();

            if (incr < 0.01) {
                incr = 0.01;
            }
            String container = goodsDetail.getPackageContainer();
            String unit = goodsDetail.getPackageUnit();
            String chargeUnit = goodsDetail.getUnit();
            double num = FormatUtil.countDivide(count , incr);
            if ("散货".equals(container)) {
                if (chargeUnit != null && chargeUnit.equals(unit)) {
                    return;
                }
                tvIntro.setText("已选: " + FormatUtil.subZeroAndDot(count + "") + chargeUnit + "( " + FormatUtil.subZeroAndDot(num + "") + unit + " )");
            } else {
                if (chargeUnit != null && chargeUnit.equals(container)) {
                    return;
                }
                tvIntro.setText("已选: " + FormatUtil.subZeroAndDot(count + "") + chargeUnit + "( " + FormatUtil.subZeroAndDot(num + "") + container + " )");
            }
            tvIntro.setVisibility(View.VISIBLE);
        }
    }

    public double calMin(GoodsDetail goodsDetail) {
        if (goodsDetail != null) {

            double leastCount = Double.valueOf(goodsDetail.getProductSpecPrice().getMoq());
            if (leastCount < 0.01) {
                leastCount = 0.01;
            }
            min = leastCount;
            incr = goodsDetail.getIncr();
            if (min < 0.01){
                min = 0.01;
            }
            if (incr < 0.01){
                incr = 0.01;
            }

        }

        return min;

    }

    public double calMax(GoodsDetail goodsDetail) {
        if (goodsDetail != null) {
            max = goodsDetail.getInventoryAmount();

        }


        return max;

    }

//    public double standardNumber(double flag) {
//        if (goodsDetail.getIncr() == 0) {
//            return flag;
//        }
//        double standardNumber;
//        double remainderNumber;
//        double timesNumber;
//        timesNumber = ((int) (flag / goodsDetail.getIncr())) * (goodsDetail.getIncr());
//        remainderNumber = goodsDetail.getIncr();
//        if (timesNumber == flag) {
//            remainderNumber = 0;
//        }
//        standardNumber = timesNumber + remainderNumber;
//        //DecimalFormat df = new DecimalFormat("#.00");
//        //df.format(standardNumber);
//        standardNumber = new BigDecimal(standardNumber).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//        return standardNumber;
//    }
}
